﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using BasePlatformNet;
using Newtonsoft.Json;
using System.IO;
using BasePlatformCommon;

namespace L9SubSet
{
	public partial class Form_EditSwitchConfig : Form
	{
		// 模式 new/edit
		private string mode = "";

		// 交换机配置文件路径 - Json 格式
		private string switchConfigFileJson = "";

		// 父窗体
		private Form_MainSet parentUI = null;

		// 底层平台引用（单例）
		private BaseCoreNet baseCoreNet = null;

		// 当前处于编辑状态的控件
		private bool editFormatAction = true;
		private DataGridViewTextBoxEditingControl editingControl; 

		// 初始化完成标记
		private bool initDone = false;

		private string section = "EditSwitch";			// 多语言文件配置节名称

		private string tip = "提示";						// MessageBox 题头

		/*****************************************************************************************/

		// 构造函数
		public Form_EditSwitchConfig(Form_MainSet parentUI, BaseCoreNet baseCoreNet, string switchConfigFileJson, string mode)
		{
			InitializeComponent();

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			this.Font = new System.Drawing.Font(this.Font.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

			this.parentUI = parentUI;
			this.baseCoreNet = baseCoreNet;
			this.switchConfigFileJson = switchConfigFileJson;
			this.mode = mode;

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}

			initUIElements(switchConfigFileJson);

			initDone = true;
		}

		// 由 Json 文件初始化界面数据
		private void initUIElements(string switchConfigFileJson)
		{
			if (switchConfigFileJson == null || switchConfigFileJson.Equals(""))
			{
				return;
			}

			// 当前的 Json 文件从系统配置文件中提取
			if (switchConfigFileJson.Equals(parentUI.useInnerSwitchDataTip))
			{
				switchConfigFileJson = parentUI.innerSwitchDataFilePath;
			}

			if (!File.Exists(switchConfigFileJson))
			{
				return;
			}

			// 解析 Json
			SwitchMapJson switchMapJson = parseSwitchConfigFromJson(switchConfigFileJson);

			if (switchMapJson != null)
			{
				foreach (SwitchMapJsonUnit unit in switchMapJson.map)
				{

					configDataGridView.Rows.Add(unit.SubIndex, formatMac(unit.Mac));
				}
			}
		}

		// 设置本地化语言
		public void setLanguageText()
		{
			if (LanguageOper.available == false)
			{
				return;
			}

			LanguageOper.SetCurrentCulture();

			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 界面控件文字
			this.Text = LanguageOper.ReadValue(section, "editSwitch.Text");
			saveOtherButton.Text = LanguageOper.ReadValue(section, "saveOtherButton.Text");
			switchInfoLabel.Text = LanguageOper.ReadValue(section, "switchInfoLabel.Text");
			okButton.Text = LanguageOper.ReadValue(section, "okButton.Text");
			cancelButton.Text = LanguageOper.ReadValue(section, "cancelButton.Text");

			// 表格列头
			configDataGridView.Columns[0].HeaderText = LanguageOper.ReadValue(section, "headerText.0");
			configDataGridView.Columns[1].HeaderText = LanguageOper.ReadValue(section, "headerText.1");
			configDataGridView.Columns[2].HeaderText = LanguageOper.ReadValue(section, "headerText.2");
		}

		// 从 Json 格式的交换机配置文件中解析数据
		public SwitchMapJson parseSwitchConfigFromJson(string configFilePath)
		{
			StreamReader reader = null;
			try
			{
				StringBuilder jsonDataBuilder = new StringBuilder();
				
				// 读取配置文件
				reader = new StreamReader(new FileStream(configFilePath, FileMode.Open));
				string currentLine = null;
				while (true)
				{
					currentLine = reader.ReadLine();
					if (currentLine == null)
					{
						break;
					}
					else
					{
						jsonDataBuilder.Append(currentLine);
					}
				}

				// 解析 Json
				SwitchMapJson switchMapJson = (SwitchMapJson)JsonConvert.DeserializeObject(jsonDataBuilder.ToString(), typeof(SwitchMapJson));

				// 检查 Mac 地址的正则表达式
				Regex r = new Regex(@"^([0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])$");

				// 检查解析后的数据
				foreach (SwitchMapJsonUnit unit in switchMapJson.map)
				{
					// 检查 SubIndex
					int subIndex = -1;
					if (int.TryParse(unit.SubIndex, out subIndex) == false)
					{
						return null;
					}
					else if (subIndex < 1)
					{
						return null;
					}

					// 检查 Mac 地址
					if (r.IsMatch(unit.Mac.Trim().Replace("-", "").Replace(":", "")))
					{
						continue;
					}
					else
					{
						return null;
					}
				}

				return switchMapJson;

			}
			catch (Exception)
			{
				return null;
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
			}
		}

		// 检查输入数据
		private bool checkData()
		{
			try
			{
				// 空数据时, 仅有 1 行
				if (configDataGridView.RowCount == 1)
				{
					return false;
				}

				// 检查 Mac 地址的正则表达式
				Regex r = new Regex(@"^([0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])$");

				bool errorFlag = false;
				for (int i = 0; i < configDataGridView.RowCount - 1; i++)
				{
					// 检查 SubIndex
					object subIndexValue = configDataGridView.Rows[i].Cells[0].Value;
					if (subIndexValue == null)
					{
						configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.Red;
						errorFlag = true;
					}
					else
					{
						string subIndexStr = configDataGridView.Rows[i].Cells[0].Value.ToString();
						int subIndex = -1;
						if (int.TryParse(subIndexStr, out subIndex) == false)
						{
							configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.Red;
							errorFlag = true;
						}
						else if (subIndex < 1)
						{
							configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.Red;
							errorFlag = true;
						}
						else
						{
							configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.White;
						}
					}

					// 检查 Mac 地址
					object macValue = configDataGridView.Rows[i].Cells[1].Value;
					if (macValue == null)
					{
						configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.Red;
						errorFlag = true;
					}
					else
					{
						string macStr = configDataGridView.Rows[i].Cells[1].Value.ToString();
						if (r.IsMatch(macStr.Trim().Replace("-", "").Replace(":", "")))
						{
							configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.White;
						}
						else
						{
							configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.Red;
							errorFlag = true;
						}
					}
				}

				return errorFlag;
			}
			catch (Exception ex)
			{
				MessageBoxEx.Show(this, ex.Message + ex.StackTrace);
				return false;
			}
		}

		// 将配置信息写入 Json 文件
		private void writeSwitchConfigFileJson(string filePath)
		{
			SwitchMapJson switchMapJson = new SwitchMapJson();
			switchMapJson.map = new List<SwitchMapJsonUnit>();

			StreamWriter sw = null;
			try
			{
				string jsonSata = "";
				sw = new StreamWriter(new FileStream(filePath, FileMode.Create));

				// 空数据时, 仅有 1 行
				if (configDataGridView.RowCount == 1)
				{
				}
				else
				{
					for (int i = 0; i < configDataGridView.RowCount - 1; i++)
					{
						string currentSubIndex, currentMac;

						// 读取 SubIndex
						object subIndexValue = configDataGridView.Rows[i].Cells[0].Value;
						if (subIndexValue == null)
						{
							currentSubIndex = "";
						}
						else
						{
							currentSubIndex = configDataGridView.Rows[i].Cells[0].Value.ToString();
						}

						// 读取 Mac 地址
						object macValue = configDataGridView.Rows[i].Cells[1].Value;
						if (macValue == null)
						{
							currentMac = "";
						}
						else
						{
							currentMac = configDataGridView.Rows[i].Cells[1].Value.ToString();
						}

						switchMapJson.map.Add(new SwitchMapJsonUnit(currentSubIndex, currentMac));
					}
				}
				jsonSata = JsonConvert.SerializeObject(switchMapJson, Formatting.Indented);
				sw.WriteLine(jsonSata);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message + ex.StackTrace);
			}
			finally
			{
				if (sw != null)
				{
					sw.Flush();
					sw.Close();
				}
			}
		}

		// 另存为
		private void saveOtherButton_Click(object sender, EventArgs e)
		{
			if (configDataGridView.RowCount > 1)
			{
				// 检查输入数据
				bool errorFlag = checkData();
				if (errorFlag == true)
				{
					configDataGridView.ClearSelection();
					string msg = "数据输入错误, 请检查";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.0");
					}
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				SaveFileDialog s = new SaveFileDialog();
				s.Filter = "Json Files(*.json)|*.json";
				DialogResult dr = s.ShowDialog();
				if (dr == DialogResult.OK)
				{
					writeSwitchConfigFileJson(s.FileName);
					string msg = "系统结构文件保存成功";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.1");
					}
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
			}
			else
			{
				configDataGridView.ClearSelection();
				string msg = "无法写入空数据";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.2");
				}
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}
		}

		// 保存并生效
		private void okButton_Click(object sender, EventArgs e)
		{
			// 检查输入数据
			bool errorFlag = checkData();
			if (errorFlag == true)
			{
				configDataGridView.ClearSelection();
				string msg = "数据输入错误, 请检查";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.0");
				}
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			// 新建模式
			if (mode.Equals("new"))
			{
				// 存在有效数据
				if (configDataGridView.RowCount > 1)
				{
					SaveFileDialog s = new SaveFileDialog();
					s.Filter = "Json Files(*.json)|*.json";
					DialogResult dr = s.ShowDialog();
					if (dr == DialogResult.OK)
					{
						writeSwitchConfigFileJson(s.FileName);
						switchConfigFileJson = s.FileName;
						
						// 重新生效配置
						if (baseCoreNet != null)
						{
							baseCoreNet.readSwitchConfigFileJson(switchConfigFileJson);
							baseCoreNet.setUseSwitch(true);
							parentUI.updateSwitchConfigFileByChild(switchConfigFileJson);
						}
						
						this.DialogResult = DialogResult.OK;
					}
				}
				// 提示写入空数据
				else
				{
					configDataGridView.ClearSelection();
					string msg = "无法写入空数据";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.2");
					}
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}
			}
			// 编辑模式
			else if (mode.Equals("edit"))
			{
				// 存在有效数据
				if (configDataGridView.RowCount > 1)
				{
					// 写入配置文件
					if (switchConfigFileJson.Equals(parentUI.useInnerSwitchDataTip))
					{
						switchConfigFileJson = parentUI.innerSwitchDataFilePath;
					}

					writeSwitchConfigFileJson(switchConfigFileJson);

					// 重新生效配置
					if (baseCoreNet != null)
					{
						baseCoreNet.readSwitchConfigFileJson(switchConfigFileJson);
						baseCoreNet.setUseSwitch(true);
					}

					this.DialogResult = DialogResult.OK;
				}
				// 提示写入空数据
				else
				{
					configDataGridView.ClearSelection();
					string msg = "无法写入空数据";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.2");
					}
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}
			}
		}

		// 取消
		private void cancelButton_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		// 窗体显示时, 清空 configDataGridView 选择
		private void Form_EditSwitchConfig_Shown(object sender, EventArgs e)
		{
			configDataGridView.ClearSelection();
		}

		// 获得应用程序 exe 所在路径
		private string getAppPath()
		{
			return (new FileInfo(Application.ExecutablePath)).Directory.ToString();
		}

		// 添加行时, 自动添加删除按钮
		private void configDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
		{
			string delStr = "删除";
			if (LanguageOper.available == true)
			{
				delStr = LanguageOper.ReadValue(section, "str.0");
			}

			for (int i = 0; i < configDataGridView.RowCount - 1; i++)
			{
				configDataGridView.Rows[i].Cells[2].Value = delStr;
			}
		}

		// 删除当前行
		private void configDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			if (configDataGridView.CurrentCell.ColumnIndex != 2)
			{
				return;
			}

			if (configDataGridView.CurrentCell.Value == null)
			{
				return;
			}

			configDataGridView.Rows.RemoveAt(configDataGridView.CurrentCell.RowIndex);
		}

		// 有控件处于编辑状态
		private void configDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
		{
			editingControl = (DataGridViewTextBoxEditingControl)e.Control;

			editingControl.TextChanged += new EventHandler(editingControl_TextChanged);
		}

		// 编辑态控件的文字默认为大写字母
		private void editingControl_TextChanged(object sender, EventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			if (configDataGridView.CurrentCell.ColumnIndex != 1)
			{
				return;
			}

			if (editFormatAction == false)
			{
				return;
			}

			string value = editingControl.Text.ToUpper();
			int selectionStart = editingControl.SelectionStart;

			editFormatAction = false;
			editingControl.Text = value;
			editingControl.SelectionStart = selectionStart;
			editingControl.ScrollToCaret();
			editFormatAction = true;
		}
		
		// mac地址格式化
		private string formatMac(string mac)
		{
			mac = mac.Replace(":", "").Replace("-", "");
			char[] chars = mac.ToCharArray();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < chars.Length; i++)
			{
				sb.Append(chars[i]);
				if (i % 2 == 1 && i != chars.Length - 1)
				{
					sb.Append("-");
				}
			}

			return sb.ToString();
		}
	
	}
}
